package com.easonji.admin.controller;

import com.easonji.admin.form.UserForm;
import com.easonji.admin.manager.DeptManager;
import com.easonji.admin.manager.UserManager;
import com.easonji.admin.query.UserQuery;
import com.easonji.admin.service.IPostService;
import com.easonji.admin.service.UserService;
import com.easonji.common.base.controller.BaseController;
import com.easonji.common.base.response.Response;
import com.easonji.common.base.response.enums.ResponseEnum;
import com.easonji.common.constant.Consts;
import com.easonji.common.constant.enums.UserStatusEnum;
import com.easonji.common.constant.enums.message.MessageEnum;
import com.easonji.common.util.StringUtils;
import com.easonji.core.annotion.Permission;
import com.easonji.core.log.LogObjectHolder;
import com.easonji.core.shiro.util.ShiroUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @ClassName: UserController
 * @Description: 用户控制器
 * @Author: LiuJun
 * @date: 2018/07/30 14:05:38
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    /**
     * 页面前缀
     */
    private final static String PREFIX = "system/user/";

    @Resource
    private UserService userService;

    @Resource
    private UserManager userManager;

    @Resource
    private DeptManager deptManager;

    @Resource
    private IPostService iPostService;

    /**
     * 跳转到用户首页
     */
    @Permission
    @GetMapping("")
    public String index() {
        return PREFIX + "user";
    }

    /**
     * 跳转到添加用户页面
     */
    @Permission
    @GetMapping("/to_add")
    public String toAdd(Model model) {
        Object posts = iPostService.queryComboList();
        model.addAttribute("postComboList",posts);
        return PREFIX + "user_add";
    }

    /**
     * 跳转到修改用户页面
     */
    @Permission
    @GetMapping("/to_update/{userId}")
    public String toUpdate(@PathVariable Integer userId, Model model) {
        Object result = userService.queryUser(userId);
        LogObjectHolder.me().set(result);
        model.addAttribute("user", result);
        Object posts = iPostService.queryComboList();
        model.addAttribute("postComboList",posts);
        return PREFIX + "user_edit";
    }

    /**
     * 跳转到角色分配页面
     */
    @Permission(Consts.ADMIN_ROLE_NAME)
    @GetMapping("/to_roleAssign/{userId}")
    public String roleAssignIndex(@PathVariable Integer userId, Model model) {
        model.addAttribute("userId", userId);
        model.addAttribute("account", userManager.getUserAccountById(userId));
        return PREFIX + "user_roleAssign";
    }

    /**
     * 跳转到应用分配页面
     */
    @GetMapping("/to_appAssign/{userId}")
    public String appAssignIndex(@PathVariable Integer userId, Model model) {
        model.addAttribute("userId", userId);
        model.addAttribute("account", userManager.getUserAccountById(userId));
        return PREFIX + "user_appAssign";
    }

    /**
     * 跳转到修改密码页面
     */
    @GetMapping("/to_chPwd")
    public String chpwdIndex() {
        return PREFIX + "user_chPwd";
    }

    /**
     * 查询用户列表
     */
    @ResponseBody
    @Permission
    @PostMapping("/list")
    public Object queryUserList(UserQuery userQuery) {
        if (!ShiroUtils.isAdmin()) {
            Integer deptId = ShiroUtils.getUser().getDeptId();
            List<Integer> deptIds = deptManager.querySubDeptIdListById(deptId);
            userQuery.setDeptIds(deptIds);
        }
        return userService.queryUserList(userQuery);
    }

    /**
     * 添加用户
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @PostMapping("/add")
    public Response addUser(@Valid UserForm userForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        // 判断账号是否重复
        Integer uerId = userManager.getUserIdByAccount(userForm.getAccount());
        if (StringUtils.isNotEmpty(uerId)) {
            return failure(MessageEnum.USER_EXISTED.getCode(), MessageEnum.USER_EXISTED.getMessage());
        }
        int result = userService.saveUser(userForm);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.SAVE_SUCCESS);
    }

    /**
     * 修改用户
     */
    @ResponseBody
    @Permission
    @PostMapping("/update")
    public Response updateUser(@Valid UserForm userForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        boolean assertAuthResult = assertAuth(userForm.getId());
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        int result = userService.updateUser(userForm);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.UPDATE_SUCCESS);
    }

    /**
     * 删除管理员
     */
    @ResponseBody
    @Permission
    @PostMapping("/remove")
    public Response removeUser(@RequestParam Integer userId) {
        if (StringUtils.isEmpty(userId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        // 不能删除超级管理员
        if (userId.equals(Consts.ADMIN_ID)) {
            return failure(MessageEnum.CANT_DELETE_ADMIN.getCode(), MessageEnum.CANT_DELETE_ADMIN.getMessage());
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        boolean result = userService.updateUserStatus(userId, UserStatusEnum.DELETED.getCode());
        if (!result) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.REMOVE_SUCCESS);
    }

    /**
     * 重置管理员的密码
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @PostMapping("/resetPwd")
    public Response resetPwd(@RequestParam Integer userId) {
        if (StringUtils.isEmpty(userId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        int result = userService.updateUserPwd(userId, Consts.DEFAULT_PWD);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.RESET_PWD_SUCCESS);
    }

    /**
     * 冻结管理员
     */
    @ResponseBody
    @Permission
    @PostMapping("/freeze")
    public Response freezeUser(@RequestParam(required = true) Integer userId) {
        if (StringUtils.isEmpty(userId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        // 不能冻结超级管理员
        if (userId.equals(Consts.ADMIN_ID)) {
            return failure(MessageEnum.CANT_FREEZE_ADMIN.getCode(), MessageEnum.CANT_FREEZE_ADMIN.getMessage());
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        boolean result = userService.updateUserStatus(userId, UserStatusEnum.FREEZED.getCode());
        if (!result) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.FREEZE_USER_SUCCESS);
    }

    /**
     * 解除冻结管理员
     */
    @ResponseBody
    @Permission
    @PostMapping("/unfreeze")
    public Response unfreezeUser(@RequestParam(required = true) Integer userId) {
        if (StringUtils.isEmpty(userId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        boolean result = userService.updateUserStatus(userId, UserStatusEnum.OK.getCode());
        if (!result) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.UNFREEZE_USER_SUCCESS);
    }

    /**
     * 分配角色
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @PostMapping("/setRole")
    public Response setRole(@RequestParam Integer userId, @RequestParam String roleIds) {
        if (StringUtils.isOneEmpty(userId, roleIds)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        // 不能修改超级管理员
        if (userId.equals(Consts.ADMIN_ID)) {
            return failure(MessageEnum.CANT_CHANGE_ROLE_ADMIN.getCode(),
                    MessageEnum.CANT_CHANGE_ROLE_ADMIN.getMessage());
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        int result = userService.updateUserRole(userId, roleIds);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.USER_ROLEASSIGN_SUCCESS);
    }

    /**
     * 分配应用
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @PostMapping("/setApp")
    public Response setApp(@RequestParam Integer userId, @RequestParam String appIds) {
        if (StringUtils.isOneEmpty(userId, appIds)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        boolean assertAuthResult = assertAuth(userId);
        if (!assertAuthResult) {
            return failure(MessageEnum.NO_PERMITION.getCode(), MessageEnum.NO_PERMITION.getMessage());
        }
        int result = userService.updateUserApp(userId, appIds);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.USER_APPASSIGN_SUCCESS);
    }

    /**
     * 修改当前用户的密码
     */
    @ResponseBody
    @PostMapping("/changePwd")
    public Response changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        if (StringUtils.isOneEmpty(oldPwd, newPwd, rePwd)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        if (!newPwd.equals(rePwd)) {
            return failure(MessageEnum.TWO_PWD_NOT_MATCH.getCode(), MessageEnum.TWO_PWD_NOT_MATCH.getMessage());
        }
        Integer userId = ShiroUtils.getUser().getUserId();
        boolean checkPwdResult = userService.checkOldPwd(userId, oldPwd);
        if (!checkPwdResult) {
            return failure(MessageEnum.OLD_PWD_NOT_RIGHT.getCode(), MessageEnum.OLD_PWD_NOT_RIGHT.getMessage());
        }
        int result = userService.updateUserPwd(userId, newPwd);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.USER_CHPWD_SUCCESS);
    }

    /**
     * 判断当前登录的用户是否有操作这个用户的权限
     * 
     * @param userId
     *            用户ID
     */
    private Boolean assertAuth(Integer userId) {
        boolean result = false;
        if (ShiroUtils.isAdmin()) {
            result = true;
        } else {
            Integer deptId = ShiroUtils.getUser().getDeptId();
            List<Integer> deptIds = deptManager.querySubDeptIdListById(deptId);
            Integer deptid = userManager.getUserDeptIdById(userId);
            if (deptIds.contains(deptid)) {
                result = true;
            }
        }
        return result;
    }
}
